const sha1 = require('sha1');
const config = require('../config');
const getRawBody = require('raw-body')

// 解析xml数据为js对象 方法一 自己封装的promise
// const parseString = require('xml2js').parseString
// function  praseXml(xml) {
//     return new Promise((resolve, reject) => {
//         parseString(xml, { trim: true,explicitArray:false,ignoreAttrs:true }, (err, result) => {
//             if (!err) {
//                 resolve(result.xml)
//             } else {
//                 reject(err)
//             }
//         })
//     })
// }

// 解析xml数据为js对象 方法二 官方的promise用法
const xml = require('xml2js');
const parser = new xml.Parser({ trim: true, explicitArray: false, ignoreAttrs: true });


const ejs = require('ejs');
let tpl = `
<xml>
  <ToUserName><![CDATA[<%-toUsername%>]]></ToUserName>
  <FromUserName><![CDATA[<%-fromUsername%>]]></FromUserName>
  <CreateTime><%=createTime%></CreateTime>
  <MsgType><![CDATA[<%=msgType%>]]></MsgType>
  <Content><![CDATA[<%-content%>]]></Content>
</xml>`
const compiled = ejs.compile(tpl);

function reply(content, fromUsername,toUsername){
    let info = {
        toUsername,
        fromUsername,
        content:content || '',
        createTime: new Date().getTime(),
        msgType :'text'
    }
    // info.toUsername = toUsername
    // info.fromUsername = fromUsername
    // info.createTime =new Date().getTime()
    // info.content = content || ''
    // info.msgType = 'text'
    return compiled(info)
}

module.exports = () => {
    return async ctx => {
        const { signature, echostr, timestamp, nonce } = ctx.query;
        const { token } = config;
        const sha1str = sha1([timestamp, nonce, token].join('')); //sha1加密
        if (ctx.method === 'GET') {
            console.log('GET', sha1str, signature);
            if (sha1str === signature) {
                return ctx.body = echostr;
            }
        } else if (ctx.method === 'POST') {
            // post接受的数据
            console.log('post', sha1str, signature);
            if (sha1str === signature) {
                const xml = await getRawBody(ctx.req, {
                    length: ctx.request.length,
                    limit: '1mb',
                    encoding: ctx.request.charset || 'utf-8'
                });
                // console.log('xml', xml);

                // 解析xml数据为js对象 方法一 自己封装的promise
                // const message = await praseXml(xml);
                // console.log('message', message);
                // if(message.Content === '111'){
                //      return ctx.body = '222';
                // }else{
                //     return ctx.body = 'success';
                // }


                // 解析xml数据为js对象 方法二 官方的promise用法
                const formatResult = await parser.parseStringPromise(xml);
                const message = formatResult.xml;
                console.log('message',message);
                let content = '';
                if (message.MsgType === 'text') {
                    content  = message.Content;
                } 
                const repltXml = reply(content,message.ToUserName,message.FromUserName)
                return ctx.body = repltXml;
            }
        }
    }
}